﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KPIS.GERP.SECURITY.App_UI.Commons;
using Telerik.Web.UI;
using System.IO;
using KPIS.GERP.SECURITY.BLL;
using KPIS.GERP.SECURITY.MODAL;
using KPIS.GERP.SECURITY.MODEL;

namespace KPIS.GERP.SECURITY.App_UI.Forms
{
    public partial class Users : System.Web.UI.Page
    {
        private UserBLL userBLL = new UserBLL();
        private RoleBLL roleBLL = new RoleBLL();
        private UserRoleBLL userRoleBLL = new UserRoleBLL();
        private PermissionBLL perBLL = new PermissionBLL();
        private HrmEmployeeBLL employeeBLL = new HrmEmployeeBLL();
        private SsMng ssMng = new SsMng();
        private MailMerge mailMerge = new MailMerge();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session["EmpSeq"] = "60";
                lblHeader.Text = "รายชื่อผู้ใช้งานระบบ ";
                OnUpdateCmdUI("VIEW");
                BindRdoEmployeeType();
            }
            if (!string.IsNullOrEmpty(Request["Export"]))
            {
                Export();
            }
        }

        private void BindRdoEmployeeType()
        {
            var tb = employeeBLL.GetEmployeeType().Tables[0];
            rdoEmployeeType.DataSource = tb;
            rdoEmployeeType.DataBind();
            rdoEmployeeType.Items.Insert(0, new ListItem("ทั้งหมด", "")
                {
                    Selected = true
                });
        }

        private void OnUpdateCmdUI(string Mode)
        {
            bool bViewMode = Mode == "VIEW";
            bool bAddNewMode = Mode == "ADDNEW";
            bool bEditMode = Mode == "EDIT";
            bool bShowMode = Mode == "SHOW";

            PanelFilter.Visible = bViewMode;
            PanelUserRole.Visible = bShowMode;

            if (bViewMode)
            {
                LoadDataGrid();
            }
            else if (bShowMode)
            {
                LoadDataGridRole();
            }
        }

        public string GetTrueFalseImage(string strCompare, string strTrue, string strFalse
                                        , string strTrueImageUrl, string strFalseImageUrl)
        {
            if (strCompare == strTrue)
                return strTrueImageUrl;
            else if (strCompare == strFalse)
                return strFalseImageUrl;
            else
                return null;
        }

        public void LoadDataGrid()
        {
            Nullable<int> EmployeeType = string.IsNullOrEmpty(rdoEmployeeType.SelectedValue) ? (int?) null : Int32.Parse(rdoEmployeeType.SelectedValue);

            DataSet ds = userBLL.LoadUser((int?) null, EmployeeType, (int?) null, "");
            DataTable dt = null;
            if (ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
                RadGrid1.DataSource = dt;
                RadGrid1.DataBind();
            }
        }

        public void LoadDataGridRole()
        {
            string SystemID = rblSystemID.SelectedValue;
            Nullable<int> UserSeq = string.IsNullOrEmpty(lblUserSeq.Text) ? (int?) null : Int32.Parse(lblUserSeq.Text);

            DataTable dt = userRoleBLL.LoadUserRoleUnion((int?) null, UserSeq, SystemID);

            RadGrid2.DataSource = dt;
            RadGrid2.DataBind();
        }

        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            Session["EMPTYPE"] = rdoEmployeeType.SelectedValue;

            if (e.CommandName == "Delete")
            {
                int Sequence = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["user_seq"]);

                userBLL.Delete(Sequence, ssMng.EmpSeqI); // Int32.Parse(Session["EmpSeq"].ToString()));
            }
            else if (e.CommandName == "ShowDetail" && e.Item is GridDataItem)
            {
                lblUserSeq.Text = RadGrid1.Items[e.Item.ItemIndex]["user_seq"].Text;
                cmdBackHome.Text = RadGrid1.Items[e.Item.ItemIndex]["user_name"].Text;

                OnUpdateCmdUI("SHOW");
            }

            LoadDataGrid();
        }

        protected void rdoEmployeeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataGrid();
        }

        protected void RadGrid2_ItemCommand(object source, GridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                int Sequence = Convert.ToInt32((e.Item as GridDataItem).OwnerTableView.DataKeyValues[e.Item.ItemIndex]["role_seq"]);

                userBLL.Delete(Sequence, ssMng.EmpSeqI); // Int32.Parse(Session["EmpSeq"].ToString()));
            }
            else if (e.CommandName == "EditView") // คลิกแก้ไข
            {
                GridDataItem item;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdEditView").Visible = false;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdUpdateALL").Visible = true;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdCancelALL").Visible = true;

                for (int i = 0; i < RadGrid2.Items.Count; i++)
                {
                    item = RadGrid2.Items[i];

                    CheckBox chkHasRole = (CheckBox) item["has_role"].FindControl("chkHasRole");
                    Image imgHasRole = (Image) item["has_role"].FindControl("imgHasRole");

                    chkHasRole.Visible = true;
                    //chkHasRole.Checked = item["has_role"].Text.Replace("&nbsp;", "") == "1";

                    imgHasRole.Visible = false;
                }

                return;
            }
            else if (e.CommandName == "UpdateAll") // คลิกบันทึก
            {
                GridDataItem item;
                string UserRoleSeq = "";
                string RoleSeq = "";

                for (int i = 0; i < RadGrid2.Items.Count; i++)
                {
                    item = RadGrid2.Items[i];

                    CheckBox chkHasRole = (CheckBox) item["has_role"].FindControl("chkHasRole");

                    RoleSeq = item["role_seq"].Text.Replace("&nbsp;", "");
                    UserRoleSeq = item["user_role_seq"].Text.Replace("&nbsp;", "");

                    if (string.IsNullOrEmpty(UserRoleSeq) && chkHasRole.Checked)
                    {
                        userRoleBLL.Insert(Int32.Parse(lblUserSeq.Text.Trim())
                                           , Int32.Parse(RoleSeq)
                                           , ssMng.EmpSeqI); // Int32.Parse(Session["EmpSeq"].ToString()));
                    }
                    else if (!string.IsNullOrEmpty(UserRoleSeq) && !chkHasRole.Checked)
                    {
                        userRoleBLL.Delete(Int32.Parse(UserRoleSeq), ssMng.EmpSeqI); // Int32.Parse(Session["EmpSeq"].ToString()));
                        //userRoleBLL.Update(Int32.Parse(UserRoleSeq)
                        //        , Int32.Parse(lblUserSeq.Text.Trim())
                        //        , Int32.Parse(RoleSeq)
                        //        , Int32.Parse(Session["EmpSeq"].ToString()));
                    }
                }
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdEditView").Visible = true;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdUpdateALL").Visible = false;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdCancelALL").Visible = false;
            }
            else if (e.CommandName == "CancelAll") // คลิกยกเลิก
            {
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdEditView").Visible = true;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdUpdateALL").Visible = false;
                RadGrid2.MasterTableView.Controls[0].Controls[0].Controls[0].FindControl("cmdCancelALL").Visible = false;
            }
            LoadDataGridRole();
        }

        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                GridDataItem dataItem = (GridDataItem) e.Item;

                CheckBox chkHasRole = (CheckBox) dataItem["has_role"].FindControl("chkHasRole");

                chkHasRole.Checked = dataItem["has_role"].Text == "1";
                chkHasRole.Visible = false;
            }
        }

        protected void rblSystemID_SelectedIndexChanged(object sender, EventArgs e)
        {
            LoadDataGridRole();
        }

        protected void cmdBackHome_Click(object sender, EventArgs e)
        {
            OnUpdateCmdUI("VIEW");
        }

        protected void Export()
        {
            string strTemplatePath = Server.MapPath("~/Reports/Templates/จดหมายเวียนแจ้งสิทธิ์การใช้งานระบบ.docx");
            string strSaveAsFileName = string.Format("จดหมายเวียนแจ้งสิทธิ์การใช้งานระบบ{0}.docx", DateTime.Now.ToString("yyyyMMddHHmmssffff"));
            string strSaveAsPath = Server.MapPath("~/Reports/Temp/");
            foreach (UserWithRoles userWithRoles in userRoleBLL.GetUserWithRoles())
            {
                Dictionary<string, string> fields = new Dictionary<string, string>();
                fields.Add("FullName", userWithRoles.FullName);
                fields.Add("Position", userWithRoles.Position);
                fields.Add("UserJobSite", userWithRoles.JobSite);
                fields.Add("Url", Request.Url.Host);
                fields.Add("Username", userWithRoles.UserName);
                fields.Add("Password", userWithRoles.Password);
                int i = 1;
                foreach (var r in userWithRoles.System)
                {  
                    fields.Add("System" + (i), userWithRoles.SystemWord(r));
                    fields.Add("Roles"+ (i), userWithRoles.RolesOfSystem(r));
                    i++;
                }
                mailMerge.MergeTemplateMulti(strTemplatePath, strSaveAsPath + strSaveAsFileName, fields, null, null, null);
            }
            mailMerge.SaveFileToClient(Response, strSaveAsPath, strSaveAsFileName, true);
        }
    }
}